<template>
    <!-- <h2>用户列表</h2>
    <el-divider></el-divider> -->
    <div class="user-management">
      <!-- Search Form Section -->
      <el-card class="search-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>用户搜索</span>
            <el-button text @click="expandSearch = !expandSearch">
              {{ expandSearch ? '收起' : '展开' }}
              <el-icon class="header-icon" :class="{ 'is-active': expandSearch }">
                <arrow-down />
              </el-icon>
            </el-button>
          </div>
        </template>
        <el-form 
          class="search-form" 
          :inline="true" 
          :model="params"
          ref="searchForm"
        >
          <el-form-item label="用户名">
            <el-input 
              v-model="params.userCode" 
              placeholder="请输入用户名" 
              clearable
              prefix-icon="User"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户类型">
            <el-select 
              v-model="params.userType" 
              placeholder="请选择用户类型" 
              clearable
            >
              <el-option 
                v-for="role of roleList" 
                :label="role.roleName" 
                :value="role.roleId" 
                :key="role.roleId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户状态">
            <el-select 
              v-model="params.userState" 
              placeholder="请选择用户状态" 
              clearable
            >
              <el-option label="禁用" value="0"></el-option>
              <el-option label="启用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getUserList">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- Main Content Card -->
      <el-card class="content-card" shadow="never">
        <!-- Action Buttons Section -->
        <div class="action-section">
          <div class="left-actions">
            <el-button type="primary" @click="openUserAdd">
              <el-icon><Plus /></el-icon>
              添加用户
            </el-button>
            <el-button @click="export2Table">
              <el-icon><Download /></el-icon>
              导出数据
            </el-button>
          </div>
          <div class="right-actions">
            <el-button 
              type="danger" 
              :disabled="!multipleSelection.length"
              @click="deleteUserList"
            >
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
          </div>
        </div>

        <!-- Table Section -->
        <div class="table-section">
          <el-table 
            :data="userList" 
            ref="multipleTableRef" 
            @selection-change="handleSelectionChange" 
            style="width: 100%" 
            border 
            stripe
            highlight-current-row
            v-loading="loading"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="userId" label="用户ID" sortable align="center" width="80" />
            <el-table-column prop="userCode" label="用户名" sortable min-width="120" show-overflow-tooltip />
            <el-table-column prop="userName" label="昵称" sortable min-width="120" show-overflow-tooltip />
            <el-table-column label="用户状态" sortable align="center" width="100">
              <template #default="{ row }">
                <el-tag 
                  :type="row.userState === '0' ? 'danger' : 'success'"
                  effect="light"
                  size="small"
                >
                  {{row.userState === "0" ? "禁用" : "启用"}}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="getCode" label="创建人" sortable min-width="120" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" sortable min-width="160" show-overflow-tooltip />
            <el-table-column label="操作" fixed="right" width="320" align="center">
              <template #default="{ row }">
                <el-space wrap size="small">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="openUserUpdate(row)"
                  >
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small"
                    @click="deleteUser(row.userId)"
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                  <el-button 
                    :type="row.userState === '1' ? 'warning' : 'success'"
                    size="small"
                    @click="updateState(row)"
                  >
                    <el-icon>
                      <el-icon v-if="row.userState === '1'"><CircleClose /></el-icon>
                      <el-icon v-else><CircleCheck /></el-icon>
                    </el-icon>
                    {{row.userState === "1" ? "禁用" : "启用"}}
                  </el-button>
                  <el-dropdown v-if="row.userState === '1'" trigger="click">
                    <el-button size="small">
                      更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="resetPwd(row.userId)">
                          <el-icon><Key /></el-icon>重置密码
                        </el-dropdown-item>
                        <el-dropdown-item @click="openAssignRole(row)">
                          <el-icon><UserFilled /></el-icon>分配角色
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- Pagination Section -->
        <div class="pagination-section">
          <el-pagination
            background
            :total="params.totalNum"
            :page-sizes="[10, 20, 30, 50]"
            v-model:page-size="params.pageSize"
            v-model:current-page="params.pageNum"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="changeSize"
            @current-change="changeCurrent"
          />
        </div>
      </el-card>

      <!-- Dialogs -->
      <user-add ref="userAddRef" @ok="getUserList"></user-add>
      <user-update ref="userUpdateRef" @ok="getUserList"></user-update>
      <assign-role ref="assignRoleRef"></assign-role>
    </div>
</template>

<script setup>
import { reactive, ref, computed } from 'vue';
import { useRouter } from 'vue-router'
import { get, put, del, tip, export2excel } from "@/common";
import { 
  Search, 
  Edit, 
  Delete, 
  Plus, 
  Download, 
  Refresh,
  ArrowDown,
  User,
  Key,
  UserFilled,
  CircleCheck,
  CircleClose 
} from '@element-plus/icons-vue'

const router = useRouter(); // 获取路由器
const loading = ref(false);
const expandSearch = ref(false);
const searchForm = ref();

// 分页模糊查询数据
const params = reactive({
  userCode: '',
  userType: '',
  userState: '',
  pageSize: 5,
  pageNum: 1,
  totalNum: 0
})

// 表格数据
const userList = ref();

// 获取查询结果
const getUserList = async () => {
  loading.value = true;
  try {
    const result = await get("/user/user-list", params);
    userList.value = result.data.resultList;
    params.totalNum = result.data.totalNum;
  } catch (error) {
    console.error('Failed to fetch user list:', error);
    tip.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
}
getUserList();

// 获取所有角色
const roleList = ref([]);
const getRoleList = () => {
  get("/role/role-list").then(result => {
    roleList.value = result.data;
  });
}
getRoleList();

// 复选框的操作
const multipleTableRef = ref();
const multipleSelection = ref([]);
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTableRef.value.clearSelection()
  }
}
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
}

// 导出数据
const export2Table = () => {
  get("/user/exportTable", params).then(result => {
    // 要导出的数据
    const userList = result.data;
    const columns = [
      {"title": "用户ID", "key": "userId"},
      {"title": "用户名", "key": "userCode"},
      {"title": "昵称", "key": "userName"},
      {"title": "用户状态", "key": "userState"},
      {"title": "创建人", "key": "getCode"},
      {"title": "创建时间", "key": "createTime"},
    ];
    export2excel(columns, userList, "员工信息表");
  });
}

// 删除用户提交
const deleteUser = (userId) => {
  del(`/user/deleteUser/${userId}`, null, { title: "提示", message: "您确定删除该用户吗？" }).then(result => {
    tip.success(result.message);
    // 重新查询
    getUserList();
  });
}

// 批量删除
const deleteUserList = () => {
  if(multipleSelection.value.length){
    // 取出所有选中的id
    const userIds = multipleSelection.value.reduce((prev, cur) =>{
      prev.push(cur.userId);
      return prev;
    }, []);

    del('/user/deleteUserList', userIds, { title: "提示", message: "您确定删除选中用户吗？" }).then(result => {
      tip.success(result.message);
      // 重新查询
      getUserList();
    });
  }else{
    tip.error("请选择需要删除的行！");
  }
}

// 修改用户状态
const updateState = (user) => {
  user.userState = user.userState=="0"?"1":"0";
  put('/user/updateState', user).then(result => {
    // 重新查询
    getUserList();
  });
}

// 重置密码
const resetPwd = (userId) => {
  put(`/user/updatePwd/${userId}`).then(result => {
    tip.success(result.message);
    // 重新查询
    getUserList();
  });
}

// 添加用户
import UserAdd from "./user-add.vue";
const userAddRef = ref();
const openUserAdd = () => {
  userAddRef.value.open();
};

// 修改用户
import UserUpdate from "./user-update.vue";
const userUpdateRef = ref();
const openUserUpdate = (row) => {
  userUpdateRef.value.open(row);
};

// 分配角色
import AssignRole from "./assign-role.vue";
const assignRoleRef = ref();
const openAssignRole = (row) => {
  assignRoleRef.value.open(row, roleList);
};

// 点击修改权限
const openUpdateAuth = (user) => {
  // 通过路由导航到修改权限页面
  // path不可以和params搭档，否则params会失效
  // router.push({ name: 'authUpdate', params: {"userId": user.userId } });
  router.push({ path: '/user/auth-update', query: {"userId": user.userId } });
};

// 修改每页显示条数
const changeSize = (size) => {
  params.pageSize = size;
  // 重新查询
  getUserList();
}
// 修改当前页码
const changeCurrent = (num) => {
  params.pageNum = num;
  // 重新查询
  getUserList();
}

// 重置搜索
const resetSearch = () => {
  searchForm.value?.resetFields();
  getUserList();
}

</script>
<style scoped>
.user-management {
  padding: 16px;
}

.search-card {
  margin-bottom: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
}

.header-icon {
  transition: transform 0.3s;
  font-size: 12px;
  margin-left: 4px;
}

.header-icon.is-active {
  transform: rotate(180deg);
}

.search-form {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.content-card {
  margin-bottom: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

.action-section {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.left-actions {
  display: flex;
  gap: 12px;
}

.right-actions {
  display: flex;
  gap: 12px;
}

.table-section {
  margin-bottom: 16px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

:deep(.el-table .el-table__header-wrapper th) {
  background-color: #fafafa;
  color: rgba(0, 0, 0, 0.85);
  font-weight: 500;
  height: 48px;
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  border-radius: 4px;
  padding: 8px 16px;
}

:deep(.el-button--small) {
  padding: 6px 12px;
}

:deep(.el-button [class*=el-icon] + span) {
  margin-left: 4px;
}

:deep(.el-form--inline .el-form-item) {
  margin-bottom: 16px;
  margin-right: 0;
}

:deep(.el-input__wrapper),
:deep(.el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px #d9d9d9 inset;
  border-radius: 4px;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

:deep(.el-pagination) {
  padding: 0;
  margin-top: 0;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
}

:deep(.el-space) {
  flex-wrap: nowrap !important;
}
</style>